const router = require("koa-router")();
const fs = require("fs")
const path = require("path")
const main = require("../models")
router.post("/doForm",async ctx=>{
    console.log(ctx.request.body);
    var {username,age,likes} = ctx.request.body;
    age = Number(age)
    console.log(ctx.request.files.pic.path);
    var filename = ctx.request.files.pic.path;
    var reader = fs.createReadStream(filename);
    var uploadFile = `./static/${path.basename(filename)}`;
    var write = fs.createWriteStream(uploadFile);
    reader.pipe(write)
    var pic = ctx.origin+"/"+path.basename(filename);

    const collection = await main('list215');
    var res = await collection.find({username}).toArray();
    if (res.length) {
        ctx.body = "<script>alert('已添加过该成员');location.href='/form'</script>"
        
    } else {
        await collection.insertOne({ username, age, likes,pic });
        await ctx.redirect("/form")
    }
})
module.exports = router;